package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.util.RandomUtil;
import com.atguigu.yygh.msm.service.MsmService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @program: yygh_parent
 * @author: Mr.Zhuo
 * @create: 2022-03-14 17:31
 **/
@RestController
@RequestMapping("/api/msm/")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("给客户发送短信服务")
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        // 服务端限制六十秒不能重复发送
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "60秒内不能重复发送");
        }

        // 1.我们需要提供给客户一个6位的短信验证码
        code = RandomUtil.getSixBitRandom();

        // 然后利用担心服务进行发送短信
        Boolean flag = msmService.sendCode(phone, code);

        if (flag) {
            // 讲短信信息存储到redis中
            redisTemplate.opsForValue().set(phone, code, 60 , TimeUnit.SECONDS);
        }
        return R.ok();
    }
}
